//
//  DDNFVC.swift
//  SinaMicroBlog
//
//  Created by dqw on 15/7/31.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
let imagCount = 4

class DDNFVC: UICollectionViewController {
    
    // MARK: - VC的初始化方法，很特别。有疑问：init 里面和外面不一致，初始化方法一般不都是很一致么。
   private let flowLayout = DDFlowLayout()
    init(){
        super.init(collectionViewLayout: flowLayout)
    }
    
    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.registerClass(DDNFCell.self, forCellWithReuseIdentifier: reuseIdentifier)
 }
    
// MARK: - 重写数据源方法。
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return imagCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! DDNFCell
        let index = indexPath.item
        cell.imageIndex = index
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
       let indexPaths = collectionView.indexPathsForVisibleItems()
        for indexP in indexPaths {
            if indexP.item == imagCount - 1 {
            let cell = collectionView.cellForItemAtIndexPath(indexP) as! DDNFCell
                cell.startButtonAnimation()
            }
        }
    }
}


// FIXME: Cell 类定义。 此处不能用private，因为其中又按钮的点击方法。
 class DDNFCell: UICollectionViewCell {
    
     override init(frame: CGRect) {
        super.init(frame: frame)
        loadAndLayouSubviews()
    }

    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
    }
    
    var imageIndex: NSInteger = 0 {
        didSet {
            backImg.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startBtn.hidden = true
        }
    }
    
    // MARK: - 加载和布局Cell的子控件。
    private func loadAndLayouSubviews() {
        
        contentView.addSubview(backImg)
        contentView.addSubview(startBtn)
        
        backImg.ff_Fill(contentView)
        
//        backImg.translatesAutoresizingMaskIntoConstraints = false
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": backImg]))
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil
//            , views: ["subview": backImg]))
        
        startBtn.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
//        startBtn.translatesAutoresizingMaskIntoConstraints = false
//        contentView.addConstraint(NSLayoutConstraint(item: startBtn, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
//       contentView.addConstraint(NSLayoutConstraint(item: startBtn, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
    }
    
    // MARK: - button的动画方法， 和约束实现的动画不同，这里要把“改变”放在动画里面。
    private func startButtonAnimation() {
        
        startBtn.hidden = false
        startBtn.userInteractionEnabled  = false
        startBtn.transform = CGAffineTransformMakeScale(0, 0)
        UIView.animateWithDuration(2.0, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 3, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
           self.startBtn.transform = CGAffineTransformIdentity

            }) { (_) -> Void in
                self.startBtn.userInteractionEnabled = true
        }
        
    }

    lazy private var backImg = UIImageView()
    lazy private var startBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        btn.sizeToFit()
        btn.addTarget(self, action: "startBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        btn.hidden = true
        return btn
    }()
    
    // MARK: - 点击按钮发送通知切换控制器。
    func startBtnClick() {
        NSNotificationCenter.defaultCenter().postNotificationName(DDSwithVCNotificaitonName, object: true)
    }
}

// MARK: - 定义 FlowLayout类，在其prepareLayout方法里面实现初始化。
private class DDFlowLayout: UICollectionViewFlowLayout {

   private override func prepareLayout() {
        super.prepareLayout()
        itemSize = (collectionView?.bounds.size)!
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
}

